package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
)

func playFile(name string, start int, serverAddr string) error {
	//test
	// log1 := getLog(name)
	// fmt.Printf("%#v\n", log1)
	//end test

	fp, err := os.Open(name)
	if err != nil {
		return err
	}
	defer fp.Close()
	reader := bufio.NewReader(fp)
	buf := bytes.NewBufferString("")
	n, err := reader.WriteTo(buf)
	if err != nil || n == 0 {
		return err
	}
	list1 := splitText(buf.String())
	for i := start; i < len(list1); i++ {
		playText(list1[i], serverAddr)
		fmt.Printf("%v:%v\n", i, list1[i])
		saveLog(name, i)
	}
	return nil
}

func playText(text, serverAddr string) error {
	conn, err := net.Dial("tcp", serverAddr+":9800")
	if err != nil {
		return err
	}
	defer conn.Close()

	length := len(text)
	//fmt.Printf("%s %08d\n", text, length)
	conn.Write([]byte(fmt.Sprintf("%8d", length)))
	conn.Write([]byte(text))

	data := []byte{}
	decoder := json.NewDecoder(conn)

	err = decoder.Decode(&data)

	return err
}

const logName = ".text2audio.log"

type MyPlayLog struct {
	Name string `json:name`
	Pos  int    `json:pos`
}

func saveLog(name string, pos int) error {
	path1, file1 := filepath.Split(name)
	m := MyPlayLog{Name: file1, Pos: pos}
	data, err := json.Marshal(m)
	if err != nil {
		return err
	}

	log1 := filepath.Join(path1, logName)

	err = ioutil.WriteFile(log1, data, 0644)

	return err
}

func getLog(name string) *MyPlayLog {
	var ret MyPlayLog
	path1, file1 := filepath.Split(name)
	log1 := filepath.Join(path1, logName)
	data, err := ioutil.ReadFile(log1)
	if err != nil {
		return nil
	}
	err = json.Unmarshal(data, &ret)
	if err != nil {
		return nil
	}
	if ret.Name != file1 {
		return nil
	}
	return &ret
}

func getLogFromDir(path1 string) *MyPlayLog {
	var ret MyPlayLog
	log1 := filepath.Join(path1, logName)
	data, err := ioutil.ReadFile(log1)
	if err != nil {
		return nil
	}
	err = json.Unmarshal(data, &ret)
	if err != nil {
		return nil
	}
	return &ret
}
